package com.tianliangedu.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.alibaba.druid.pool.DruidDataSource;

public class DruidUtil {
	public static DruidDataSource dataSource=null;
	public static boolean isInit=false;
	public static void init(String driverClass,String url,String username,String password){
		 //1,创建Druid连接池对象
        dataSource = new DruidDataSource();
        //2,为数据库添加配置文件
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
	}
	
	public static Connection getConnection(String driverClass,String url,String username,String password) throws SQLException{
		if(!isInit){
			init(driverClass,url,username,password);
			isInit=true;
		}
		return dataSource.getConnection();
	}
	
	public static ResultSet getSQLResult(Connection conn,String sql){
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
	        ps=conn.prepareStatement(sql);
	        rs=ps.executeQuery();
	        return rs;
		} catch (Exception e) {
		  	e.printStackTrace();
		} 
        return null;
	}
	
	public static void main(String[] args) throws SQLException{
		String driverClass="com.mysql.jdbc.Driver";
        String url="jdbc:mysql://localhost:3306/tl";
        String username="root";
        String password="bigspark2017..";
        
        String sql="SELECT * FROM tb_class_category";
        
        Connection conn=getConnection(driverClass,url,username,password);
        ResultSet rs=getSQLResult(conn,sql);
        while (rs.next()) {
            System.out.println(rs.getInt("id")+","+rs.getString("name")+","+rs.getString("class_name"));
        }
        rs.close();
        conn.close();
        dataSource.close();
    }
}
